package ru.home.documentmanager.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import ru.home.documentmanager.model.User;
import ru.home.documentmanager.model.UserData;
import ru.home.documentmanager.model.dto.UserDataDTO;
import ru.home.documentmanager.service.UserDataService;
import ru.home.documentmanager.service.UserService;

@Controller
public class DataController extends AppController {

    @Resource
    private UserDataService userDataService;

    @Resource
    private UserService userService;

    @RequestMapping("/data")
    public ModelAndView data() {
        User user = getCurrentUser();
        UserData data = userDataService.findByUser(user);
        if (data == null) {
            data = new UserData();
            data.setUser(user);
            userDataService.save(data);
        }
        ModelAndView mav = new ModelAndView();
        UserDataDTO userDataDTO = new UserDataDTO(data);
        mav.addObject("userData", userDataDTO);
        mav.setViewName("user/data");
        return mav;
    }

    @RequestMapping("/data/save")
    public String save(@ModelAttribute("userData") UserDataDTO userDataDTO) {
        User user = getCurrentUser();
        System.out.println("user:" + user);
        UserData data = userDataService.findByUser(user);
        System.out.println(data);
        userDataDTO.fillUserData(data);
        data.setUser(user);
        userDataService.update(data);
        return "redirect:/welcome";
    }

}
